import json
from datetime import date, datetime


class JsonMapping:
    def to_common_result(self, data, is_success=True, msg_code='', msg_text=''):
        cs = {}
        cs['is_success'] = is_success;
        cs['msg_code'] = msg_code
        cs['msg_text'] = msg_text
        cs['data'] = data
        # for test
        cs['total'] = 100
        return cs

    def dump_to_json(self, data):
        cs = self.to_common_result(data)
        return json.dumps(cs, cls=CustomJsonEncoder)


class CustomJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        # if isinstance(obj, datetime.datetime):
        #     return int(mktime(obj.timetuple()))
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)
